import { computed, defineComponent, ref, toRefs } from "vue";
import { FormInstance } from "@arco-design/web-vue";
import TitanFormItem from "@/components/form/src/TitanFormItem";
import { availFormKeys, formProps, exposedKeys } from "./form-types";

export default defineComponent({
  name: "TitanForm",
  props: formProps,
  emits: ["submit-form", "submit-success", "submit-failed"],
  setup(props, { expose, attrs, slots, emit }) {
    const { model, layoutRow, column } = toRefs(props);

    const mergeObject = computed(() => ({ ...props, ...attrs }));
    const _formProps = computed(() =>
      availFormKeys.reduce((total: any, key) => {
        if (mergeObject.value[key as keyof typeof mergeObject.value] !== undefined) {
          total[key] = mergeObject.value[key as keyof typeof mergeObject.value];
        }
        return total;
      }, {})
    );
    const refForm = ref<FormInstance>();

    const RenderFormItem = (item: any) => {
      return (
        <TitanFormItem
          {...{ column: item, form: model.value }}
          key={JSON.stringify(item)}
        />
      );
    };

    expose(
      {
        form: refForm,
      }
      // exposedKeys.reduce((total: any, item) => {
      //   if (refForm.value) {
      //     total[item as keyof typeof total] = refForm.value[item as keyof typeof refForm.value];
      //   }
      //   return total;
      // }, {})
    );

    return () => {
      let t: any[];
      if (layoutRow.value) {
        t = [
          <a-row {...(layoutRow.value || {})}>
            {column.value.map((item: any) => (
              <a-col {...(item.layout || {})}>{RenderFormItem(item)}</a-col>
            ))}
          </a-row>,
        ];
      } else {
        t = [column.value.map((item: any) => RenderFormItem(item))];
      }

      return (
        <a-form
          ref={refForm}
          {..._formProps.value}
          onSubmit={() => emit("submit-form")}
          onSubmit-success={() => emit("submit-success")}
          onSubmit-failed={() => emit("submit-failed")}
        >
          {t}
          {slots.default ? slots.default() : ""}
        </a-form>
      );
    };
  },
});
